package com.icarcom.cn.api;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;

import com.alibaba.fastjson.JSON;
import com.icarcom.cn.ui.LoginActivity;
import com.icarcom.cn.util.L;
import com.icarcom.cn.util.SP;
import com.icarcom.cn.util.SpContent;
import com.icarcom.cn.util.T;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.request.BaseRequest;

import org.json.JSONObject;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2020/5/18.
 *
 * jl
 */

public class HttpUtils implements HttpCallBack{

    public static void doGet(final Context context, final int action, Map<String, String> params, CacheMode cacheMode, final boolean showLoadingDialog, final HttpCallBack httpCallBack) {
        String url = getGetUrl(action, params);
        OkGo.get(url)
                .cacheKey(getUrl(action).toString())
                .tag(getUrl(action).toString())
                .headers("Authorization","bearer "+ SP.get(context, SpContent.userToken,"").toString())
                .cacheMode(cacheMode)
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        L.e("url:" + request.getUrl());
                        L.e("method:" + request.getMethod());
                        if (showLoadingDialog)
                            httpCallBack.showLoadingDialog();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        L.e("??????result:" + s);
                        try {
                            //成功
                            JSONObject jsonObject = new JSONObject(s);
                            boolean RespCode = jsonObject.getBoolean("State");
                            //失败

                            if (!RespCode) {
                                T.show(jsonObject.getString("Message"));
                            } else {
                                httpCallBack.onSuccess(action, s);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        if (response != null) {
                            int httpCode = response.code();
                            switch (httpCode) {
                                case 400:
                                    L.e("请求的语法出错");
                                    T.show("请求的语法出错");
                                    break;
                                case 401:
                                    L.e("未授权");
                                    T.show("未授权");
                                    break;
                                case 403:
                                    L.e("请求被拒绝");
                                    T.show("请求被拒绝");
                                    break;
                                case 404:
                                    L.e("请求的接口不存在");
                                    T.show("请求的接口不存在");
                                    break;
                                case 408:
                                    L.e("请求超时");
                                    T.show("请求超时");
                                    break;
                                case 500:
                                    L.e("服务器错误");
                                    T.show("服务器错误");
                                    break;
                                case 503:
                                    L.e("服务器停机或正在维护");
                                    T.show("服务器停机或正在维护");
                                    break;
                            }
                            L.e(e.getMessage());
                        }
                    }

                });
    }

    public static void doPost(final Context context, final int action,Object params, CacheMode cacheMode, final boolean showLoadingDialog, final HttpCallBack httpCallBack) {
        //前面一个是post,后面一个是Get,可以为空
        String url = getUrl(action).toString();

        String json_fast = JSON.toJSONString(params);

        OkGo.post(url)
                .cacheKey(String.valueOf(action))
                .tag(String.valueOf(action))
                .cacheMode(cacheMode)
                .upJson(json_fast)
                .headers("token",SP.get(context, SpContent.userToken,"").toString())
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);

                        if (showLoadingDialog)
                            httpCallBack.showLoadingDialog();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        L.e("result:" + s);
                        try {
                            //成功
                            JSONObject jsonObject = new JSONObject(s);
                            String RespCode = jsonObject.getString("retCode");
                            if(RespCode.equals("000009")||RespCode.equals("000010")){
                                SP.put(context, SpContent.isLogin, "0");
                                SP.put(context,SpContent.userToken,"");
                                context.startActivity(new Intent(context, LoginActivity.class));
                            }else {
                                httpCallBack.onSuccess(action, s);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        if (response == null)
                            return;
                        int httpCode = response.code();
                        switch (httpCode) {
                            case 400:
                                T.show("请求的语法出错");
                                break;
                            case 401:
                                T.show("未授权");
                                break;
                            case 403:
                                T.show("请求被拒绝");
                                break;
                            case 404:
                                T.show("请求的接口不存在");
                                break;
                            case 408:
                                T.show("请求超时");
                                break;
                            case 500:
                                T.show("服务器错误");
                                break;
                            case 503:
                                T.show("服务器停机或正在维护");
                                break;
                        }
                        L.e(e.getMessage());
                    }
                });
    }


    @Override
    public void onSuccess(int action, String res) {
        switch (action){
        }
    }

    @Override
    public void showLoadingDialog() {

    }

    @Override
    public void showErrorMessage(String s) {

    }

    public interface UploadCallBack {
        void onSuccess(int action, String res);

        void showErrorMessage(String s);

        void onProgress(long currentSize, long totalSize, float progress, long networkSpeed);
    }


    /**
     * 拼接get请求的url地址
     *
     * @param action
     * @param params
     * @return
     */
    public static String getGetUrl(int action, Map<String, String> params) {

        StringBuilder url = getUrl(action);

        if (params == null || params.isEmpty()) {
            return url.toString();
        }

        url.append("?");

        for (String key : params.keySet()) {
            url.append(key);
            url.append("=");
            url.append(params.get(key));
            url.append("&");
        }

        return url.toString();
    }

    public static StringBuilder getUrl(int Action) {
        StringBuilder url = new StringBuilder(UrlConstants.BASE_URL);
        String actionUrl = "";
        switch (Action) {
            case ACTION.TESTLOGIN:
                actionUrl = UrlConstants.TESTLOGIN;
                break;
            case ACTION.GETTYPEBYDEVICE:
                actionUrl = UrlConstants.GETTYPEBYDEVICE;
                break;
            case ACTION.GETEWEIMADDATA:
                actionUrl = UrlConstants.GETEWEIMADDATA;
                break;
        }
        url.append(actionUrl);
        return url;
    }
}
